import $H from '@/common/lib/request.js';
export default {
	state:{
		list:[],
		// 选中列表（存放选中的id）
		selectedList:[]
	},
	getters:{
		//判断是否全选
		checkedAll(state){
			return state.list.length === state.selectedList.length;
		},
		//价格合计
		totalPrice:(state)=>{
			var total = 0
			state.list.forEach(value=>{
				if(state.selectedList.indexOf(value.PID) > -1 ){
					total += value.PRESENT_PRICE * value.goods_count
				}
			})
			return parseInt(total);
		},
		
		// 禁用全选
		disableSelectAll:(state)=>{
			return state.list.length === 0
		}
	},
	mutations:{
		//给state里面的属性赋值
		setlist(state,n){
			state.list = n;
		},
		// 选中/取消选中某个商品
		selectItem(state,index){
			let PID = state.list[index].PID;
			let i = state.selectedList.indexOf(PID)
			
			if(i > -1){
				// 取消当前商品选中状态
				state.list[index].checked = false;
				return state.selectedList.splice(i,1);
			}
			// 选中
			state.list[index].checked = true
			state.selectedList.push(PID)
		},
		//全选
		selectAll(state){
			state.selectedList = state.list.map(item=>{
				item.checked = true;
				return item.PID
			})
		},
		
		// 取消全选
		unSelectAll(state){
			state.list.forEach(v=>{
				// 设置选中状态
				v.checked = false
			})
			state.selectedList = []
		},
		
		//删除
		delGoods(state,){
			state.list = state.list.filter(v=>{
				return state.selectedList.indexOf(v.PID) === -1
			})
		}
	},
	actions:{
		doSelectAll({commit,getters}){
			getters.checkedAll?commit('unSelectAll'):commit('selectAll')
		},
		doDelGoods({commit,state}){
			uni.showModal({
				content: '是否删除选中',
				success: (res)=>{
					if (res.confirm) {
						$H.post('/order/delete',{
							goodpid:state.selectedList
						},{
							token:true
						}).then(res=>{
							commit('delGoods')
							commit('unSelectAll')
							uni.showToast({
								title: '删除成功'
							});
						})
						
					} 
				}
			})
		}
	}
}